package api_day05;
/*
    队列的链式结构实现
 */
public class LinkedQueue {
    //队首标记head
    private Node head;
    //队尾标记rear
    private Node rear;
    //队列长度
    private int size;
    //无参构造方法，用于初始化值
    public LinkedQueue() {
        head = new Node();
        rear = head;
        size = 0;
    }
    //入队方法
    public void push(Object obj){
        Node newNode = new Node(obj);
        //如果为空队列，则队首队尾同时指向插入的节点
        if (size == 0){
            head = newNode;
            rear = newNode;
        }else {
            //非空队列的情况下
            if (head.next == null) head.next = newNode;
            rear.next = newNode;
            rear = newNode;
        }
        size++;
    }
    public Object pop(){
        if (size == 0) return null;
        Object o;
        if (head.next != null){
            o = head.data;
            head = head.next;
        }else {
            o = null;
            head = null;
            rear = null;
        }
        size--;
        return o;
    }
    public Object peek(){
        if (size == 0) return null;
        return head.data;
    }
    @Override
    public String toString() {
        StringBuilder out = new StringBuilder();
        if (size != 0){
            out.append("从队首至队尾：");
            Node current = head;
            while (current.next != null){
                out.append(current.data + ",");
                current = current.next;
            }
            out.append(current.data + ",");
            out.deleteCharAt(out.length()-1);
        }else {
            out.append("队列为空");
        }
        return out.toString();
    }
    private class Node{
        Object data;
        Node next;
        public Node() {
        }
        public Node(Object data) {
            this.data = data;
        }
    }
}
